package com.wanxi.service.impl;

import com.wanxi.dao.impl.UserDaoImpl;
import com.wanxi.dto.UserDto;
import com.wanxi.model.UserModel;
import com.wanxi.service.UserService;
import com.wanxi.util.MD5;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDaoImpl userDaoImpl = new UserDaoImpl();

    public String add(UserModel model) {
        /**
         * 逻辑处理：
         * 1.判断当前用户是否存在
         * 2.如果存在，则返回error，用户名已存在
         * 3.否则直接保存，并返回success
         */
        boolean isHave = userDaoImpl.findByUsername(model);
        if (isHave) {
            return "same username";
        } else {
//            需要对密码进行加密
            String mingwen = model.getPassword();
            String anwen = MD5.encoderByMd5(mingwen);
            model.setPassword(anwen);
            int count = userDaoImpl.add(model);
            if (count > 0) {
                return "success";
            } else {
                return "error";
            }

        }
    }

    public String update(UserModel model) {
        /**
         * 如果可以修改用户账号
         * 1.判断当前用户账号是否和自己本身一致，如果账号和自己一样，说没有修改
         * 2.如果不一样，说明想修改，需要判断是否在数据库里面存在
         * -------------------------------------
         * 默认 不允许修改账号：
         *
         */
        if (model.getId() == -1) {
            return "error";
        }
        String mingwen = model.getPassword();
        String anwen = MD5.encoderByMd5(mingwen);
        model.setPassword(anwen);
        int count = userDaoImpl.update(model);
        if (count > 0) {
            return "success";
        } else {
            return "error";
        }
    }

    public String delete(UserModel model) {
        if (model.getId() == -1) {
            return "error";
        }
        int count = userDaoImpl.delete(model);
        if (count > 0) {
            return "success";
        } else {
            return "error";
        }
    }

    public UserDto findById(UserModel model) {
        return userDaoImpl.findById(model);
    }

    public List<UserDto> findAll(UserModel model) {
        return userDaoImpl.findAll(model);
    }

    public int count(UserModel model) {

        return userDaoImpl.count(model);
    }

    /**
     * 根据用户名和密码判断数据库是否存在当前用户
     *
     * @param model
     * @return
     */
    @Override
    public String login(UserModel model) {
        if (!model.getCode().equals(model.getSCode())) {
            return "error-code";
        }
        String mingwen = model.getPassword();
        String anwen = MD5.encoderByMd5(mingwen);
        model.setPassword(anwen);
        UserDto userDto = userDaoImpl.findByUsernameAndPassword(model);
        if (userDto == null) {
            return "error";

        } else {
            return "success";
        }

    }
}
